﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MODEL;
using DAL;
using Common;

namespace Service
{
    public class UserService : IUserService
    {
        public async Task<IEnumerable<User>> GetUsersAsync(UserQueryCriteria criteria = null)
        {
            return await UserDAL.QueryUsersAsync(criteria);   
        }

        public async Task<IEnumerable<string>> QueryUserIndustry()
        {
            return await UserDAL.QueryUserIndustryAsync();
        }

        public bool LogOn(string account, string password)
        {
            string passwordMD5InDB = UserDAL.GetPasswordMD5(account);

            if (string.IsNullOrEmpty(passwordMD5InDB))
            {
                return false;
            }
            //if (passwordMD5InDB == password.ToMD5()) // 此处是为了调试临时去掉了的。提交代码时要删掉
            if (passwordMD5InDB == password)
            {

                User user = UserDAL.QueryUsersAsync(new UserQueryCriteria { UserId = account }).Result.FirstOrDefault();
                if (user == null)
                {
                    throw new Exception("该用户信息缺失");
                }
                user.role = RoleDAL.QueryRole(user.Id).Result.FirstOrDefault();
                if (user.role == null)
                {
                    throw new Exception("无法识别该用户角色");
                }

                AppSetting.Instance.User = user;
                return true;
            }
            else
            {
                return false;
            }
        }

        public bool ExistUser(string account)
        {
           return UserDAL.QueryUsersAsync(new UserQueryCriteria { UserId = account }).Result.SafeCheck();
        }

        public async Task<int> AddUser(string account, string password, string userName)
        {
            return await UserDAL.AddNewUserAsync(account, password, userName);
        }

        public async Task<int> DeleteUser(int userId)
        {
            return await UserDAL.DeleteUser(userId);
        }

        public async Task<int> UpdateUserState(int userId, string state)
        {
            return await UserDAL.UpdateUserState(userId, state);
        }      
    }
}
